package db;

import base.*;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.rms.*;

/**
 *
 * @author Shayan
 */
public class CategoryManager {

    private final static String CATEGORY_TABLE = "CATEGORIES";

    public static void persist(Category category) 
            throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, IOException {
        RecordStore rs = RecordStore.openRecordStore(CATEGORY_TABLE, true);

        persist(rs, category);

        rs.closeRecordStore();
    }

    public static void persist(ArrayOfCategory categories) 
            throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, IOException {
        RecordStore rs = RecordStore.openRecordStore(CATEGORY_TABLE, true);

        for (int i = 0; i < categories.getCategories().length; i++) {
            persist(rs, categories.getCategories()[i]);
        }

        rs.closeRecordStore();
    }

    private static void persist(RecordStore rs, Category category)
            throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException {
        byte[] data = category.getData();

        int recordId = DatabaseHelper.findRecordId(rs, category.getId());
        if (recordId == -1) {
            rs.addRecord(data, 0, data.length);
        } else {
            rs.setRecord(recordId, data, 0, data.length);
        }
    }

    public static Category getById(String id) 
            throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, IOException {
        RecordStore rs = RecordStore.openRecordStore(CATEGORY_TABLE, true);

        Category result = null;
        byte[] data = DatabaseHelper.findRecordById(rs, id);
        if (data!=null) {
            result = Category.create(data);
        }

        rs.closeRecordStore();
        return result;
    }

    public static Category getByName(String id)
            throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, IOException {
        RecordStore rs = RecordStore.openRecordStore(CATEGORY_TABLE, true);

        Category result = null;
        byte[] data = DatabaseHelper.findRecordByName(rs, id);
        if (data!=null) {
            result = Category.create(data);
        }

        rs.closeRecordStore();
        return result;
    }

    public static Vector getAll() throws RecordStoreException, IOException {
        RecordStore rs = RecordStore.openRecordStore(CATEGORY_TABLE, true);

        Vector result = new Vector();

        RecordEnumeration re = rs.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            result.addElement(Category.create(re.nextRecord()));
        }

        rs.closeRecordStore();
        return result;
    }
}
